import {CloseOutlined, PlusOutlined} from '@ant-design/icons';
import {Card, Col, Divider, Image, Input, message, Row, Tag, Badge, Modal, Table, Avatar, Popconfirm} from 'antd';
import React, {Component, useState, useRef, useEffect} from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { connect } from 'umi';
import Articles from './components/Articles';
import Likes from './components/Likes';
import Stars from './components/Stars';
import styles from './Center.less';
import { TweenOneGroup } from 'rc-tween-one';
import {updateUserInfo} from "@/pages/UserSet/service";
import {deleteAction, deleteBlog} from "@/pages/UserCenter/service";
import {history} from "@@/core/history";
import EyeOutlined from "@ant-design/icons/EyeOutlined";
import {cancelFollow, getCurrentUser} from "@/pages/UserInfo/service";



const TagList = ({ tagList, currentUser }) => {
  const [tags, setTags] = useState(tagList);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, []);

  const handleClose = (removedTag) => {
    const newTags = tags.filter(tag => tag.key !== removedTag);
    setTags(newTags);
    refrshTags(newTags, '删除');
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    let newTags = tags;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      newTags.push({
        key: newTags.length + '',
        label: inputValue
      })
      setTags([...newTags]);
      refrshTags(newTags, '添加');
    }
    setInputVisible(false);
    setInputValue('');
  };

  const refrshTags = (newTags, action) => {
    let tagStr = '';
    newTags.map((item) => {
      tagStr += item.label + ',';
    })
    tagStr = tagStr.replace(/,$/gi, '');
    let params = {
      id: currentUser.id,
      tags: tagStr
    }
    updateUserInfo({...params}).then(res => {
      if (res.status == 200){
        message.info(action + '成功！');
      }
    })
  }

  const forMap = (tag) => {
    const tagElem = (
      <Tag
        closable
        onClose={e => {
          e.preventDefault();
          handleClose(tag.key);
        }}
      >
        {tag.label}
      </Tag>
    );
    return (
      <span style={{ display: 'inline-block' }}>
        {tagElem}
      </span>
    );
  };

  const tagChild = tags.map(forMap);
  return (
    <>
      <div style={{ marginBottom: 16 }}>
        <TweenOneGroup
          enter={{
            scale: 0.8,
            opacity: 0,
            type: 'from',
            duration: 100,
          }}
          onEnd={e => {
            if (e.type === 'appear' || e.type === 'enter') {
              e.target.style = 'display: inline-block';
            }
          }}
          leave={{ opacity: 0, width: 0, scale: 0, duration: 200 }}
          appear={false}
        >
          {tagChild}
        </TweenOneGroup>
      </div>
      {inputVisible && (
        <Input
          ref={inputRef}
          type="text"
          size="small"
          style={{ width: 78 }}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (
        <Tag onClick={showInput} className="site-tag-plus" style={{ cursor: 'pointer' }}>
          <PlusOutlined/> 新增
        </Tag>
      )}
    </>
  );
};

class UserCenter extends Component {

  state = {
    tabKey: 'articles',
    modalName: '',
    modalVisible: false,
    data: []
  };

  input = undefined;

  columns = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      align: 'center',
      render: (text, record) => <Avatar style={{cursor: 'pointer'}} src={text} onClick={() => this.toUserInfo(record.id)}/>
    },
    {
      title: '用户名',
      dataIndex: 'loginname',
      align: 'center',
      key: 'loginname',
    },
    {
      title: '关注时间',
      dataIndex: 'flow_time',
      align: 'center',
      key: 'flow_time',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <a style={{fontSize: '12px'}} onClick={() => this.toUserInfo(record.id)}><EyeOutlined />查看</a>
          <Popconfirm
            title={this.state.modalName == '我的关注' ? '确定取消关注吗？' : '确定移除吗？'}
            onConfirm={this.state.modalName == '我的关注' ? () => this.handleCancelFollow(record.id) : () => this.deleteFan(record.id)}
            okText="是"
            cancelText="否"
          >
            <a style={{fontSize: '12px', marginLeft: '5%'}}><CloseOutlined />{this.state.modalName == '我的关注' ? '取消关注' : '移除'}</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userCenter/fetchCurrent',
    }).then( e => {
      const { currentUser } = this.props;
      dispatch({
        type: 'userCenter/fetchByUser',
        payload: {
          userId: currentUser.id
        }
      });

      dispatch({
        type: 'userCenter/fetchLikes',
        payload: {
          userId: currentUser.id,
          actionType: 'blog_like'
        }
      });

      dispatch({
        type: 'userCenter/fetchStars',
        payload: {
          userId: currentUser.id,
          actionType: 'blog_star'
        }
      });
    })
  };

  queryLikes = (pageSize) => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'userCenter/fetchLikes',
      payload: {
        userId: currentUser.id,
        actionType: 'blog_like',
        pageSize: pageSize
      }
    });
  };

  queryStars = (pageSize) => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'userCenter/fetchStars',
      payload: {
        userId: currentUser.id,
        actionType: 'blog_star',
        pageSize: pageSize
      }
    });
  };

  delBlog = id => {
    const { dispatch, currentUser } = this.props;
    deleteBlog({id: id}).then(res => {
      if (res.status == 200){
        dispatch({
          type: 'userCenter/fetchByUser',
          payload: {
            userId: currentUser.id
          }
        });
        message.success('删除成功！');
      }
    })
  };

  delAction = id => {
    const { dispatch, currentUser } = this.props;
    deleteAction({id: id}).then(res => {
      if (res.status == 200){
        dispatch({
          type: 'userCenter/fetchByUser',
          payload: {
            userId: currentUser.id
          }
        });
        dispatch({
          type: 'userCenter/fetchLikes',
          payload: {
            userId: currentUser.id,
            actionType: 'blog_like'
          }
        });
        dispatch({
          type: 'userCenter/fetchStars',
          payload: {
            userId: currentUser.id,
            actionType: 'blog_star'
          }
        });
        message.success('删除成功！');
      }
    })
  };

  onTabChange = (key) => {
    this.setState({
      tabKey: key,
    });
  };

  renderChildrenByTabKey = (tabKey) => {
    if (tabKey === 'articles') {
      return <Articles delBlog={this.delBlog}/>;
    }

    if (tabKey === 'likes'){
      return <Likes delLike={this.delAction} fetch={this.queryLikes}/>;
    }

    if (tabKey === 'stars'){
      return <Stars delStar={this.delAction} fetch={this.queryStars}/>;
    }

    return null;
  };

  handleModal = (flag, name, data) => {
    this.setState({
      modalVisible: flag,
      modalName: name,
      data: data
    })
  };

  toUserInfo = id => {
    history.push('/userInfo?id=' + id);
  };

  handleCancelFollow = id => {
    const { currentUser } = this.props;
    cancelFollow({
      userId: currentUser.id,
      flowUserId: id
    }).then(res => {
      if (res.status === 200){
        this.refreshUser();
        message.success('取关成功！');
        this.handleModal(false, '', []);
      }
    })
  };

  deleteFan= id => {
    const { currentUser } = this.props;
    cancelFollow({
      userId: id,
      flowUserId: currentUser.id
    }).then(res => {
      if (res.status === 200){
        this.refreshUser();
        message.success('移除成功！');
        this.handleModal(false, '', []);
      }
    })
  };

  refreshUser = () => {
    const { dispatch } = this.props;
    getCurrentUser().then(u => {
      if (u.status == 200){
        window.top.user = u.data;
        dispatch({
          type: 'userCenter/fetchCurrent'
        })
      }
    })
  }

  render() {
    const { tabKey, modalVisible, modalName, data } = this.state;
    const { currentUser = {}, list = {}, likes = {}, stars = {}, currentUserLoading } = this.props;
    const dataLoading = currentUserLoading || !(currentUser && Object.keys(currentUser).length);
    const operationTabList = [
      {
        key: 'articles',
        tab: (
          <span>
            <Badge count={list ? list.length : 0} offset={[12, 1]} style={{ backgroundColor: '#1ac480' }}>
              我的博客
            </Badge>
            <span
              style={{
                fontSize: 12,
              }}
            >
            </span>
          </span>
        ),
      },
      {
        key: 'likes',
        tab: (
          <span>
            <Badge count={likes.list ? likes.list.length : 0} offset={[12, 1]} style={{ backgroundColor: 'rgba(255,69,0,0.91)' }}>
              我的点赞
            </Badge>
            <span
              style={{
                fontSize: 12,
              }}
            >
            </span>
          </span>
        ),
      },
      {
        key: 'stars',
        tab: (
          <span>
            <Badge count={stars.list ? stars.list.length : 0} offset={[12, 1]} style={{ backgroundColor: '#3DAEFF' }}>
              我的收藏
            </Badge>
            <span
              style={{
                fontSize: 12,
              }}
            >
            </span>
          </span>
        ),
      },
    ];
    return (
      <GridContent>
        <Row gutter={24}>
          <Col lg={7} md={24}>
            <Card
              bordered={false}
              style={{
                marginBottom: 24,
              }}
              loading={dataLoading}
            >
              {!dataLoading && (
                <div>
                  <div className={styles.avatarHolder}>
                    <Image alt="" src={currentUser.avatar} />
                    <div className={styles.name}>{currentUser.name}</div>
                    <div>
                      <span onClick={() => this.handleModal(true, '我的关注', window.top.user.follows)} style={{cursor: 'pointer'}}>关注：<a>{window.top.user.follows.length}</a></span>
                      <span onClick={() => this.handleModal(true, '我的粉丝', window.top.user.fans)} style={{marginLeft: '2%', cursor: 'pointer'}}>粉丝：<a>{window.top.user.fans.length}</a></span>
                    </div>
                    <div style={{marginTop: '2%'}}>{currentUser.signature}</div>
                  </div>
                  <Divider dashed />
                  <TagList currentUser={currentUser} tagList={currentUser.tags || []} />
                  <Divider
                    style={{
                      marginTop: 16,
                    }}
                    dashed
                  />
                </div>
              )}
            </Card>
          </Col>
          <Col lg={17} md={24}>
            <Card
              className={styles.tabsCard}
              bordered={false}
              tabList={operationTabList}
              activeTabKey={tabKey}
              onTabChange={this.onTabChange}
            >
              {this.renderChildrenByTabKey(tabKey)}
            </Card>
          </Col>
        </Row>
        {modalVisible &&
        <Modal width={600} title={modalName} visible={modalVisible} onOk={() => this.handleModal(false, '', [])} onCancel={() => this.handleModal(false, '', [])}>
          <Row>
            <Col span={24}>
              <Table footer={null} pagination={false} dataSource={data} columns={this.columns} />
            </Col>
          </Row>
        </Modal>}
      </GridContent>
    );
  }
}

export default connect(({ loading, userCenter }) => ({
  currentUser: userCenter.currentUser,
  currentUserLoading: loading.effects['userCenter/fetchCurrent'],
  list: userCenter.list,
  likes: userCenter.likes,
  stars: userCenter.stars
}))(UserCenter);
